package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppGroup;
import com.ruoyi.app.domain.bo.AppGroupBo;
import com.ruoyi.app.domain.bo.AppGroupUserBo;
import com.ruoyi.app.domain.vo.AppGroupUserVo;
import com.ruoyi.app.domain.vo.AppGroupVo;
import com.ruoyi.app.mapper.AppGroupMapper;
import com.ruoyi.app.service.IAppGroupService;
import com.ruoyi.app.service.IAppGroupUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.GroupUser;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * APP群组Service业务层处理
 *
 * @author heike
 * @date 2023-01-29
 */
@RequiredArgsConstructor
@Service
public class AppGroupServiceImpl implements IAppGroupService {

    private final AppGroupMapper baseMapper;

    private final IAppGroupUserService appGroupUserService;

    /**
     * 查询APP群组
     */
    @Override
    public AppGroupVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    @Override
    public AppGroupVo queryByGroupId(String groupId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<AppGroup>().eq(AppGroup::getGroupId, groupId));
    }

    /**
     * 查询APP群组列表
     */
    @Override
    public TableDataInfo<AppGroupVo> queryPageList(AppGroupBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppGroup> lqw = buildQueryWrapper(bo);
        Page<AppGroupVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP群组列表
     */
    @Override
    public List<AppGroupVo> queryList(AppGroupBo bo) {
        LambdaQueryWrapper<AppGroup> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    /**
     * 查询APP群组列表
     */
    @Override
    public List<AppGroupVo> queryNameList(AppGroupBo bo) {
        LambdaQueryWrapper<AppGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getGroupId()), AppGroup::getGroupId, bo.getGroupId())
            .or()
            .like(StringUtils.isNotBlank(bo.getName()), AppGroup::getName, bo.getName());
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppGroup> buildQueryWrapper(AppGroupBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getGroupId()), AppGroup::getGroupId, bo.getGroupId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), AppGroup::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), AppGroup::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getAllowinvites()), AppGroup::getAllowinvites, bo.getAllowinvites());
        lqw.eq(StringUtils.isNotBlank(bo.getMembersonly()), AppGroup::getMembersonly, bo.getMembersonly());
        lqw.eq(StringUtils.isNotBlank(bo.getInviteNeedConfirm()), AppGroup::getInviteNeedConfirm, bo.getInviteNeedConfirm());
        lqw.eq(StringUtils.isNotBlank(bo.getDisabled()), AppGroup::getDisabled, bo.getDisabled());
        lqw.eq(StringUtils.isNotBlank(bo.getCustom()), AppGroup::getCustom, bo.getCustom());
        return lqw;
    }

    /**
     * 新增APP群组
     */
    @Override
    public Boolean insertByBo(AppGroupBo bo) {
        AppGroup add = BeanUtil.toBean(bo, AppGroup.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createGroup(AppGroupBo bo, Long userId, List<String> ids) {
        //保存群组
        bo.setDisabled(Constants.SUCCESS);
        if (insertByBo(bo)) {
            //保存用户成员
            AppGroupUserBo groupUserBo = new AppGroupUserBo();
            groupUserBo.setUserId(userId);
            groupUserBo.setGroupId(bo.getId());
            groupUserBo.setPlace(GroupUser.MASTER.getCode());
            groupUserBo.setStatus(Constants.SUCCESS);
            appGroupUserService.insertByBo(groupUserBo);
            ids.forEach(e -> {
                if (StringUtils.isNotBlank(e)) {
                    AppGroupUserBo appGroupUserBo = new AppGroupUserBo();
                    appGroupUserBo.setUserId(Long.valueOf(e));
                    appGroupUserBo.setGroupId(bo.getId());
                    appGroupUserBo.setPlace(GroupUser.MEMBER.getCode());
                    appGroupUserBo.setStatus(Constants.SUCCESS);
                    appGroupUserService.insertByBo(appGroupUserBo);
                }
            });
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void joinGroup(List<String> userIds, Long groupId) {
        userIds.forEach(e -> {
            if (StringUtils.isNotBlank(e)) {
                Long id = Long.valueOf(e);
                AppGroupUserVo appGroupUserVo = appGroupUserService.queryByGroupAndUserId(groupId, id);
                if (Objects.isNull(appGroupUserVo)) {
                    AppGroupUserBo appGroupUserBo = new AppGroupUserBo();
                    appGroupUserBo.setUserId(id);
                    appGroupUserBo.setGroupId(groupId);
                    appGroupUserBo.setPlace(GroupUser.MEMBER.getCode());
                    appGroupUserBo.setStatus(Constants.SUCCESS);
                    appGroupUserService.insertByBo(appGroupUserBo);
                }
            }
        });
    }

    @Override
    public Boolean joinGroup(Long userId, Long groupId) {
        AppGroupUserVo appGroupUserVo = appGroupUserService.queryByGroupAndUserId(groupId, userId);
        if (Objects.isNull(appGroupUserVo)) {
            AppGroupUserBo appGroupUserBo = new AppGroupUserBo();
            appGroupUserBo.setUserId(userId);
            appGroupUserBo.setGroupId(groupId);
            appGroupUserBo.setPlace(GroupUser.MEMBER.getCode());
            appGroupUserBo.setStatus(Constants.SUCCESS);
            appGroupUserService.insertByBo(appGroupUserBo);
            return true;
        }
        return false;
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }

    /**
     * 修改APP群组
     */
    @Override
    public Boolean updateByBo(AppGroupBo bo) {
        AppGroup update = BeanUtil.toBean(bo, AppGroup.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean updateByVo(AppGroupVo vo) {
        AppGroup update = BeanUtil.toBean(vo, AppGroup.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppGroup entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP群组
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
